package com.tju.resource.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.mapper.TbOrderMapper;
import com.tju.resource.model.TbOrder;
import com.tju.resource.server.SysParamsService;
import com.tju.resource.server.TbCommandService;
import com.tju.resource.server.TbOrderService;
import com.tju.resource.server.TbProdPlanService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.EmptyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class TbOrderServiceImpl implements TbOrderService {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private TbProdPlanService pService;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private ChineseExceptionUtils zh_CH;
    @Autowired
    private SysParamsService paramsServiceService;
    @Autowired
    private TbCommandService tbCommandService;

    /**
     * 查询订单
     *
     * @return 订单列表
     */
    @Override
    public Result<Object> selectTbOrderList(ClientParameters parameter) {
        try {
            Integer pageNum = parameter.getPage();  //页码
            Integer limit = parameter.getLimit(); //页数量
            if (EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(limit)) { //不等于空
                pageNum = pageNum == 0 ? 1 : pageNum;
                limit = limit == 0 ? 10 : limit;
                Page<TbOrder> page = new Page<>(pageNum, limit);
                IPage<TbOrder> iPage = tbOrderMapper.selectPage(page, QueryWrapperOrder(parameter));
                for (TbOrder order : iPage.getRecords()) {  //循环订单号
                    order.setPlanNumber(pService.getProds(order.getId())); //用订单号算出生产计划数量
                }
                return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
            } else {
                ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR);
    }

    /**
     * 添加订单
     *
     * @param order 订单信息
     * @return
     */
    @Override
    @Transactional
    public Result<Object> insertTbOrder(TbOrder order) {
        try {
            if (EmptyUtils.isNotEmpty(checkOrderNumberUnique(order.getOrderNumber()))) {
                return ResultUtil.success(ResultEnum.UNKONW_ERROR, "订单号重复了：" + order.getOrderNumber());
            }
            long data = (order.getDelivery().getTime() - sdf.parse(sdf.format(new Date())).getTime()) / (24 * 3600 * 1000);
            long paramsValue = Long.parseLong(paramsServiceService.get("OD_DELIVERY").getParamsValue());
            if (data < paramsValue) {
                return ResultUtil.success(ResultEnum.UNKONW_ERROR, "交期时间必须大于订单时间" + paramsValue + "天");
            }
            order.setCreateTime(new Date());
            if (tbOrderMapper.insert(order) > 0) {
                if (pService.addEpt(order) > 0) {
                    return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.AddedSuccessfully);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.AddFailed);
    }

    /**
     * 修改订单
     *
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Result<Object> updateTbOrder(TbOrder order) {
        try {
            TbOrder tbOrder = tbOrderMapper.selectById(order.getId());
            if (!tbOrder.getOrderNumber().equals(order.getOrderNumber())) {
                if (EmptyUtils.isNotEmpty(checkOrderNumberUnique(order.getOrderNumber()))) {
                    return ResultUtil.success(ResultEnum.UNKONW_ERROR, "订单号重复了：" + order.getOrderNumber());
                }
            }
            long data = (order.getDelivery().getTime() - sdf.parse(sdf.format(tbOrder.getCreateTime())).getTime()) / (24 * 3600 * 1000);
            long paramsValue = Long.parseLong(paramsServiceService.get("OD_DELIVERY").getParamsValue());
            if (data < paramsValue) {
                return ResultUtil.success(ResultEnum.UNKONW_ERROR, "交期时间必须大于订单时间：" + paramsValue + "天");
            }

            Long prods = pService.getProds(order.getId());
            prods = prods == null ? 0L : prods;
            if (order.getOrderPcs() >= prods) {
                order.setUpdateTime(new Date());
                if (tbOrderMapper.updateById(order) > 0) {
                    return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyModified);
                }
            } else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "订单数不能小于计划数!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailToEdit);
    }

    /**
     * 删除订单
     *
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Result<Object> deleteTbOrder(TbOrder order) {
        try {
            if (EmptyUtils.isNotEmpty(order.getId())) {
                if (pService.getByOR(order.getId()).size() != 0) {//根据订单号查询是否存在生产计划
                    return ResultUtil.success(ResultEnum.UNKONW_ERROR, "当前订单下存在生产计划，不允许删除！");
                } else if (tbCommandService.getByOrderId(order.getId()).size() != 0) {//根据订单号查询是否存在指令号
                    return ResultUtil.success(ResultEnum.UNKONW_ERROR, "当前订单下存在指令号，不允许删除！");
                }
                //不存在就删除
                if (tbOrderMapper.deleteById(order.getId()) > 0) {
                    return ResultUtil.success(ResultEnum.SUCCESS, zh_CH.SuccessfullyDeleted);
                }
            } else {
                ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.MissingParameters);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, zh_CH.FailedToDelete);
    }

    /**
     * 导出订单
     *
     * @return
     */
    @Override
    public Result<Object> exportOrder(ClientParameters parameter) {
        try {
            List<TbOrder> tbOrders = tbOrderMapper.selectList(QueryWrapperOrder(parameter));
            if (tbOrders.size() != 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, tbOrders);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "导出失败,无数据!");
    }

    /**
     * 导出订单
     *
     * @return
     */
    @Override
    public Result<Object> importOrder(File file) {
        return null;
    }

    /**
     * 判断唯一的订单
     *
     * @param
     * @return
     */
    public TbOrder checkOrderNumberUnique(String orderNumber) {
        QueryWrapper<TbOrder> qw = new QueryWrapper<>();
        qw.eq("order_number", orderNumber);
        return tbOrderMapper.selectOne(qw);
    }

    /**
     * 订单查询条件
     *
     * @param parameter 参数
     * @return
     */
    public QueryWrapper<TbOrder> QueryWrapperOrder(ClientParameters parameter) {
        QueryWrapper<TbOrder> qw = new QueryWrapper<>();
        String one = parameter.getOne(); //订单号
        String two = parameter.getTwo(); //指令号
        String ugc = parameter.getUgc(); //客户名称
        String beginDate = parameter.getBeginDate(); //交期时间
        String finishDate = parameter.getFinishDate(); //交期时间
        if (EmptyUtils.isNotEmpty(one)) {
            qw.like("order_number", one);
        }
        if (EmptyUtils.isNotEmpty(two)) {
            qw.like("command_number", two);
        }
        if (EmptyUtils.isNotEmpty(ugc)) {
            qw.like("client_name", ugc);
        }
        if (EmptyUtils.isNotEmpty(beginDate) && EmptyUtils.isNotEmpty(finishDate)) {
            qw.between("delivery", beginDate, finishDate);
        }
        qw.orderByDesc("id");
        return qw;
    }
}




